package com.pixeljet.activityninja.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.HeadElement;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.user.client.DOM;

public class ActivityNinja {
	
	private boolean ninja = false;
	private boolean developmentMode = false;
	public static String URL = "http://activityninja.appspot.com/";
	public static String DEV_URL = "http://127.0.0.1:8889/";
	public static String THE_URL = URL;
	
	
	public ActivityNinja(EventBus eventBus) {
		eventBus.addHandler(
		        PlaceChangeEvent.TYPE, new PlaceChangeEvent.Handler() {
		          public void onPlaceChange(PlaceChangeEvent event) {
		        	  boolean shouldNinja = GWT.isProdMode() || developmentMode;
		        	  if(ninja && shouldNinja) recordMovement(event);
		          }
		 });
	}

	protected void recordMovement(PlaceChangeEvent event) {
		Place placeToNinja = event.getNewPlace();
		try {
			SimplePlace place = (SimplePlace) placeToNinja;
			ninja(place.getName());
			GWT.log("Recorded place movement");
		} catch (ClassCastException e) {
			GWT.log("Please implement SimplePlace in your place class: " + placeToNinja.getClass().toString());
		}
	}

	private native void ninja(String name) /*-{
		var ninja = $wnd.ninja;
		if(ninja) {
			ninja(name);
		} else {
			var temp = "ninja(" + name + ");"
			setTimeout(temp, 5000);
		}
	}-*/;

	private void includeScript() {
		String url = THE_URL + "ninja/ninja.nocache.js";
		ScriptElement scriptElement = DOM.createElement("script").cast();
		scriptElement.setSrc(url);
		HeadElement head = HeadElement.as(Document.get().getElementsByTagName("head").getItem(0));
		head.appendChild(scriptElement);
	}

	public void beginNinja() {
		ninja = true;
	}
	
	public void endNinja() {
		ninja = false;
	}

	/**
	 * Setting to true will send data to the server even in development mode. Defaults to false.
	 * @param developmentMode
	 */
	public void setDevelopmentMode(boolean developmentMode) {
		this.developmentMode = developmentMode;
	}

	public boolean isDevelopmentMode() {
		return developmentMode;
	}
	
}
